<!-- 用户管理 -->
{% extends 'layouts/default.html' %}
{% set title = '用户' %}
{% set menuActive = 'system' %}
{% block container %}
<div class="row">
    <div class="col-lg-2">
        <nav class="side-menu">
            <div class="side-menu-label d-flex align-items-center">系统</div>
            <ul class="side-menu-list">
                <li><a class="active">用户</a></li>
                <li><a href="/system/products">产品</a></li>
            </ul>
            <div class="side-menu-label d-flex align-items-center">客户</div>
            <ul class="side-menu-list mb-3">
                <li><a href="/system/link-types">联系类别</a></li>
                <li><a href="/system/stages">客户阶段</a></li>
                <li><a href="/system/tags">客户标签</a></li>
                <li><a href="/system/dataset">数据收集</a></li>
            </ul>
        </nav>
    </div>
    <div class="col-lg-10">
        <div class="h4 mb-4">系统 - 用户</div>
        <div class="d-flex flex-column">
            <div class="d-flex flex-column">
                <div class="d-flex align-items-center justify-content-between flex-wrap">
                    <form id="searchForm" method="get" class="d-flex align-items-center my-1">
                        <div><input id="queryName" class="form-control" type="search" name="name"
                                value="{{ query.name }}" placeholder="名称" /></div>
                        <div class="ms-1"><button id="queryBtn" class="btn btn-dark" type="submit">搜索</button></div>
                    </form>
                    <div class="d-flex align-items-center my-1">
                        <div class="d-flex align-items-center flex-wrap">
                            <button id="toolbarNew"
                                class="btn btn-dark btn-action d-flex justify-content-center align-items-center"
                                onclick="app.new()" data-toggle="tooltip" title="新增客户">
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor"
                                    class="bi bi-plus-lg" viewBox="0 0 16 16">
                                    <path fill-rule="evenodd"
                                        d="M8 2a.5.5 0 0 1 .5.5v5h5a.5.5 0 0 1 0 1h-5v5a.5.5 0 0 1-1 0v-5h-5a.5.5 0 0 1 0-1h5v-5A.5.5 0 0 1 8 2Z" />
                                </svg>
                            </button>
                        </div>
                        <div class="ms-3 d-flex align-items-center flex-wrap">
                            <button id="toolbarRefresh" onclick="app.search()" data-toggle="tooltip" title="刷新"
                                class="btn btn-dark btn-action ms-1 d-flex justify-content-center align-items-center">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor"
                                    class="bi bi-arrow-clockwise" width="24" height="24" viewBox="0 0 16 16">
                                    <path fill-rule="evenodd"
                                        d="M8 3a5 5 0 1 0 4.546 2.914.5.5 0 0 1 .908-.417A6 6 0 1 1 8 2v1z" />
                                    <path
                                        d="M8 4.466V.534a.25.25 0 0 1 .41-.192l2.36 1.966c.12.1.12.284 0 .384L8.41 4.658A.25.25 0 0 1 8 4.466z" />
                                </svg>
                            </button>
                            <button id="toolbarPrevPage" onclick="app.pageTo('prev')" data-toggle="tooltip" title="上一页"
                                {{ "" if pagination.hasPrevious else "disabled" }}
                                class="btn btn-dark ms-1 btn-action d-flex justify-content-center align-items-center">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor"
                                    class="bi bi-arrow-left-short" width="24" height="24" viewBox="0 0 16 16">
                                    <path fill-rule="evenodd"
                                        d="M12 8a.5.5 0 0 1-.5.5H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H11.5a.5.5 0 0 1 .5.5z" />
                                </svg>
                            </button>
                            <button id="toolbarNextPage" onclick="app.pageTo('next')" data-toggle="tooltip" title="下一页"
                                {{ "" if pagination.hasNext else "disabled" }}
                                class="btn btn-dark btn-action ms-1 d-flex justify-content-center align-items-center">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor"
                                    class="bi bi-arrow-right-short" width="24" height="24" viewBox="0 0 16 16">
                                    <path fill-rule="evenodd"
                                        d="M4 8a.5.5 0 0 1 .5-.5h5.793L8.146 5.354a.5.5 0 1 1 .708-.708l3 3a.5.5 0 0 1 0 .708l-3 3a.5.5 0 0 1-.708-.708L10.293 8.5H4.5A.5.5 0 0 1 4 8z" />
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="d-flex flex-column mt-3">
                    <div class="table-responsive">
                        <table class="table table-bordered table-group-divider table-light">
                            <thead>
                                <tr>
                                    <th scope="col">ID</th>
                                    <th scope="col">名称</th>
                                    <th scope="col">邮箱</th>
                                    <th scope="col">电话</th>
                                    <th scope="col">锁定</th>
                                    <th scope="col" style="min-width: 200px;width: 200px;">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for user in users %}
                                <tr id="user-{{user.id}}">
                                    <th scope="row">{{user.id}}</th>
                                    <td>{{user.name}}</td>
                                    <td>{{user.email}}</td>
                                    <td>{{user.phone}}</td>
                                    <td><span class="badge {{'bg-danger' if user.isLocked else 'bg-success'}}">{{'已锁定'
                                            if
                                            user.isLocked else '未锁定'}}</span></td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <button type="button" class="btn btn-sm btn-dark"
                                                onclick="window.open('/activities?userId={{user.id}}', 'blank')">动态</button>
                                            <button type="button" class="btn btn-sm btn-dark ms-1"
                                                onclick="app.edit('{{user.id}}')">编辑</button>
                                            {% if user.id !== 1 %}
                                            {% if user.isLocked %}
                                            <button type="button" class="btn btn-sm btn-danger ms-1"
                                                onclick="app.unlock('{{user.id}}')">解锁</button>
                                            {% else %}
                                            <button type="button" class="btn btn-sm btn-danger ms-1"
                                                onclick="app.lock('{{user.id}}')">锁定</button>
                                            {% endif %}
                                            {% endif %}
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock container %}
{% block script %}
<script>
    const editor = {
        title: '编辑',
        data: {},
        render() {
            const model = this;
            const editorEl = document.createElement('div');
            editorEl.id = 'editor';
            editorEl.className = 'modal fade';
            editorEl.setAttribute('aria-hidden', 'true');
            editorEl.setAttribute('tabindex', '-1');
            editorEl.setAttribute('data-bs-backdrop', 'static');
            editorEl.addEventListener('hidden.bs.modal', () => {
                model.data = {}; // clear data
                document.body.removeChild(editorEl);
            });
            document.body.appendChild(editorEl);
            editorEl.innerHTML = `
                <div class="modal-dialog modal-dialog-scrollable modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">${model.title}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <form id="editorForm">
                            <div class="d-flex flex-column">
                                <div class="mb-3 row">
                                    <label for="inputName" class="col-sm-2 col-form-label">名称</label>
                                    <div class="col-sm-10">
                                        <input type="text" class="form-control" name="name" id="inputName" autocomplete="username" value="${model.data.name || ''}"  minLength="1" required>
                                    </div>
                                </div>
                                <div class="mb-3 row">
                                    <label for="inputPhone" class="col-sm-2 col-form-label">电话</label>
                                    <div class="col-sm-10">
                                        <input type="text" class="form-control" name="phone" id="inputPhone" autocomplete="phone" value="${model.data.phone || ''}" minLength="1">
                                    </div>
                                </div>
                                <div class="mb-3 row">
                                    <label for="inputEmail" class="col-sm-2 col-form-label">邮件</label>
                                    <div class="col-sm-10">
                                        <input type="text" class="form-control" name="email" id="inputEmail" autocomplete="email" value="${model.data.email || ''}" minLength="3">
                                    </div>
                                </div>
                                <div class="mb-3 row">
                                    <label for="inputPassword" class="col-sm-2 col-form-label">密码</label>
                                    <div class="col-sm-10">
                                        <input type="password" class="form-control" name="password" id="inputPassword" autocomplete="current-password">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                            <button type="button" class="btn btn-dark">保存</button>
                        </div>
                        </form>
                    </div>
                </div>
            `;
            document.querySelector('#editor .btn-dark').addEventListener('click', () => {
                const user = editor.data;
                new FormData(document.getElementById('editorForm')).forEach((v, k) => user[k] = v);
                const url = user.id ? `/system/users/${user.id}` : '/system/users';
                $.ajax({
                    type: 'post',
                    url,
                    data: user
                }).done(function (result) {
                    const { hasError, message, data } = result;
                    if (!hasError) {
                        helper.toast(message, 'success');
                        // reload page is disgusting, wait 3 for refresh?
                        // setTimeout(() => {
                        let search = window.location.search;
                        window.location.href = `./users${search}`;
                        // }, 3000);
                    } else {
                        helper.toast(message, 'danger');
                    }
                }).always(function () {
                    $('#editor').modal('hide');
                });
            });

            $('#editor').modal('show');
        },
        open(title, data) {
            editor.title = title;
            editor.data = data || {};
            editor.render();
        },
    };

    const app = {
        data: {
            skip: '{{query.skip}}',
            limit: '{{query.limit}}',
            count: '{{pagination.count}}'
        },
        search() {
            const form = document.getElementById('searchForm');
            const formData = new FormData(form);
            formData.append('skip', app.data.skip);
            formData.append('limit', app.data.limit);
            const queryStr = new URLSearchParams(formData).toString();
            window.location.href = `?${queryStr}`;
        },
        pageTo(d) {
            if (d === 'prev') app.data.skip = Math.max(0, app.data.skip - app.data.limit);
            else app.data.skip = Math.min(app.data.count, app.data.skip + app.data.limit);
            this.search();
        },
        lock(userId) {
            helper.confirm('锁定该用户吗？', function () {
                $.ajax({
                    url: `/system/users/${userId}/lock`,
                    type: 'put',
                }).done(function () {
                    helper.toast('操作成功', 'success');
                    document.querySelectorAll(`#user-${userId} td`)[3].innerHTML = '<span class="badge bg-danger">已锁定</span>';
                    document.querySelectorAll(`#user-${userId} td`)[4].innerHTML = `
                        <div class="d-flex align-items-center">
                            <button type="button" class="btn btn-sm btn-dark" onclick="window.open('/activities?userId=${userId}', 'blank')">动态</button>
                            <button type="button" class="btn btn-sm btn-dark ms-1" onclick="app.edit('${userId}')">编辑</button>
                            <button type="button" class="btn btn-sm btn-danger ms-1" onclick="app.unlock('${userId}')">解锁</button>
                        </div>
                    `;
                });
            });
        },
        unlock(userId) {
            helper.confirm('解锁该用户吗？', function () {
                $.ajax({
                    url: `/system/users/${userId}/unlock`,
                    type: 'put',
                }).done(function () {
                    helper.toast('操作成功', 'success');
                    document.querySelectorAll(`#user-${userId} td`)[3].innerHTML = '<span class="badge bg-success">未锁定</span>';
                    document.querySelectorAll(`#user-${userId} td`)[4].innerHTML = `
                            <div class="d-flex align-items-center">
                                <button type="button" class="btn btn-sm btn-dark" onclick="window.open('/activities?userId=${userId}', 'blank')">动态</button>
                                <button type="button" class="btn btn-sm btn-dark ms-1" onclick="app.edit('${userId}')">编辑</button>
                                <button type="button" class="btn btn-sm btn-danger ms-1" onclick="app.lock('${userId}')">锁定</button>
                            </div>
                       `;
                });
            });
        },
        new() {
            editor.open('新建', { user: {} });
        },
        edit(userId) {
            $.getJSON(`/system/users/${userId}`).then((data) => editor.open('编辑', data));
        }
    };
</script>
{% endblock script %}